<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="活动名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入活动名称" clearable size="small"/>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="客户端" prop="wxClientId" v-has-role="['admin']">
        <el-select v-model="queryParams.wxClientId" placeholder="请选择客户端" clearable size="small">
          <el-option
            v-for="item in clientList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ypp:config:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ypp:config:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ypp:config:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ypp:config:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="活动编码" align="center" prop="code" />
      <el-table-column label="活动名称" align="center" prop="name" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
<!--      <el-table-column label="活动类型" align="center" prop="configType" />-->
      <el-table-column label="消耗值" align="center" prop="consumption" />

      <el-table-column label="客户端" align="center" prop="wxClientId" :formatter="clientFormat" v-has-role="['admin']"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ypp:config:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ypp:config:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改抽奖活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">

        <el-form-item label="客户端" prop="wxClientId" :required="true" v-has-role="['admin']">
          <el-select v-model="form.wxClientId" placeholder="请选择客户端" :disabled="form.id>0">
            <el-option
              v-for="item in clientList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="活动编码" prop="code" >
          <el-input v-model="form.code" placeholder="请输入活动编码" />
        </el-form-item>

        <el-form-item label="活动名称" prop="name" >
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>

<!--        <el-form-item label="配置类型">-->
<!--          <el-select v-model="form.configType" placeholder="请选择配置类型">-->
<!--            <el-option label="请选择字典生成" value="" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="抽奖时间" prop="dates">-->
<!--          {{form.dates}}-->
<!--          <el-date-picker-->
<!--            v-model="form.dates"-->
<!--            type="daterange" value-format="yyyy-MM-dd" :default-time="['00:00:00', '23:59:59']"-->
<!--            range-separator="至" @blur="handleTimestamp" @input="testClick"  unlink-panels-->
<!--            start-placeholder="开始日期"-->
<!--            end-placeholder="结束日期">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->

        <el-form-item label="抽奖时间" prop="startTime" >

          <el-date-picker
            v-model="form.dates"
            type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>

        </el-form-item>

        <el-form-item label="免费次数" prop="freeNum" >
          <el-input-number v-model="form.freeNum" placeholder="请输入消耗值" />
        </el-form-item>

        <el-form-item label="重置免费" prop="resetFree" >
          <el-input-number v-model="form.resetFree" placeholder="请输入消耗值" />
          <div style="color: #666;">隔几天重置免费,0不重置</div>
        </el-form-item>

        <el-form-item label="消耗值" prop="consumption">
          <el-input v-model="form.consumption" placeholder="请输入消耗值" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConfig, getConfig, delConfig, addConfig, updateConfig, exportConfig } from "@/api/ypp/config";
import { listClient } from "@/api/wx/client";
import { parseTime  } from "@/utils/ruoyi";

export default {
  name: "Config",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 抽奖活动表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wxClientId: undefined,
        status: undefined,
        configType: undefined,
        consumption: undefined,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

        startTime: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        awardEndTime: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        freeNum: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        resetFree: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
      },
      clientList:[]
    };
  },
  created() {
    this.getList();
    this.getDicts("ypp_award_config_status").then(response => {
      this.statusOptions = response.data;
    });
    listClient().then(response => {
      this.clientList = response.rows;
    });
  },
  methods: {
    /** 查询抽奖活动列表 */
    getList() {
      this.loading = true;
      listConfig(this.queryParams).then(response => {
        this.configList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    clientFormat(row, column) {
      let txt = '';
      this.clientList.filter(e=>{
        if (e.id == row.wxClientId){
          txt = e.name;
          return;
        }
      });
      return txt;
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        wxClientId: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        status: "1",
        consumption: undefined,
        delFlag: undefined,
        dates: [],
        startTime: undefined,
        awardEndTime: undefined,
        name: undefined,
        code: undefined,
        freeNum: 0,
        resetFree: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加抽奖活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getConfig(id).then(response => {
        this.form = response.data;
        if (this.form.startTime && this.form.awardEndTime){
          let dates = [this.getDateString(this.form.startTime),this.getDateString(this.form.awardEndTime)]
          this.$set(this.form,'dates',dates)
        }
        this.open = true;
        this.title = "修改抽奖活动";
      });
    },
    getDateString(val){
      if(val && val.length < 12){
        return val + ' 00:00:00';
      }
      return val;
    },
    /** 提交按钮 */
    submitForm: function() {
      if (this.form.dates && this.form.dates.length>1){
        var startTime = this.form.dates[0];
        var awardEndTime = this.form.dates[1];

        this.form.startTime = startTime;
        this.form.awardEndTime = awardEndTime;
      }else{
        this.msgError("抽奖时间未设置")
        return
      }
      this.$refs["form"].validate(valid => {
        if (valid) {



          if (this.form.id != undefined) {
            updateConfig(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addConfig(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除抽奖活动编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delConfig(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有抽奖活动数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportConfig(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },

  }
};
</script>
